#!/usr/bin/env python
# -*- coding: utf-8 -*-
from hashlib import md5
import requests

username = str()
password = str()
INDEX_URL = r'http://10.0.109.2'
LOGIN_URL = INDEX_URL

calg = '12345678'
ps = 1
pid = '1'

R1 = '0'
R2 = '1'
OMKKey = '123456'
para = '00'

def login(username, password):
    tmpchar = pid + password + calg;
    password = md5(tmpchar).hexdigest() + calg + pid;
    req = requests.Session()
    #req.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36'
    #req.headers['HOST'] = 'www.doctorcom.com'
    #index = req.get(INDEX_URL)
    #print index.content
    R2 = '1'

    headers = {
        'Host':'10.0.109.2',
        'Content-Length':98,
        'Origin':'http://10.0.109.2',
        'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36',
        'Content-Type':'application/x-www-form-urlencoded',
        'Referer':'http://10.0.109.2'
    }
    
    payload = {
        'DDDDD': username,
        'upass': password,
        'R1': R1,
        'R2': R2,
        'para': para,
        '0MKKey': OMKKey
    }

    post = req.post(LOGIN_URL, headers=headers, data=payload)
    print post.content
    with open("t.html", "w") as f:
        f.write(post.content)

    return post

if __name__ == '__main__':
    import os

    username = '201140701005' #None
    password = 'tobewhatwewant' #None
    login(username, password)
    exit(0)
    if not os.path.isfile('./userinfo.txt'):
        print "First Use This Script!!!"
        username = raw_input("UserName: ")
        password = raw_input("PassWord: ")
        with open('./userinfo.txt', 'w') as uif:
            uif.write(username+'\n'+password+'\n')
    else:
        print "Make sure you UserName & PassWord in file `userinfo.txt` is Right"
        with open('./userinfo.txt', 'r') as uif:
            username = uif.readline().strip()
            password = uif.readline().strip()

    if username == "" or password == "":
        print "Username or Password cannot be empty."
        print "Please Check Your Input or File `userinfo.txt` "
        exit()
    
    login(username, password)
